<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()

const isAdmin = computed(() => userStore.user?.role === 'admin')
const displayName = computed(() => userStore.user?.username ?? '')

// 下拉显示状态
const showDropdown = ref(false)

function toggleDropdown() {
  showDropdown.value = !showDropdown.value
}

function logout() {
  userStore.logout()
  router.push('/login')
  showDropdown.value = false
}

// 点击页面其他地方关闭下拉
function handleClickOutside(e) {
  const dropdownEl = document.querySelector('.user-dropdown')
  if (dropdownEl && !dropdownEl.contains(e.target)) {
    showDropdown.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark px-3">
  <a class="navbar-brand fw-bold text-white" href="#">Pubot发版工具</a>
  <div class="collapse navbar-collapse">
    <ul class="navbar-nav me-auto">
      <li class="nav-item"><router-link to="/" class="nav-link">首页</router-link></li>
      <li class="nav-item"><router-link to="/tasks" class="nav-link">任务管理</router-link></li>
      <li class="nav-item" v-if="isAdmin"><router-link to="/users" class="nav-link">用户管理</router-link></li>
    </ul>

    <!-- 用户下拉菜单 -->
    <div v-if="displayName" class="dropdown user-dropdown position-relative">
      <a class="nav-link text-white" href="javascript:void(0)" @click.prevent="toggleDropdown">
        {{ displayName }}
      </a>
      <ul
        v-show="showDropdown"
        class="dropdown-menu dropdown-menu-end show"
        style="position: absolute; top: 100%; right: 0;"
      >
        <li>
          <a class="dropdown-item" @click="logout">退出</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
</template>

<style scoped>
/* Bootstrap dropdown-menu 默认 display:none，这里用 Vue 控制显示 */
.dropdown-menu.show {
  display: block;
}
</style>
